package com.edwin.ws.webservice;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.jws.WebService;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.edwin.springjdbc.dao.AddNumberDao;
import com.edwin.springjdbc.dto.AddNumberDto;

@SuppressWarnings("restriction")
@WebService(serviceName = "addService", portName = "addServicePort", endpointInterface = "com.edwin.ws.webservice.WebServiceSample")
public class WebServiceSampleImpl implements WebServiceSample {
	
	private ApplicationContext ctx;
	private AddNumberDao addNumberdao;
	
	private final String uploadFile = "C:/tmp/";


	public Integer addServiceFromDb(){
		Integer tempInt=0;
		ctx=new ClassPathXmlApplicationContext("classpath:spring/beans.xml");
		addNumberdao=(AddNumberDao) ctx.getBean("addNumberDao");
		List<AddNumberDto> list=addNumberdao.getAddNumberDtos();
		for(AddNumberDto addNumberDto : list){
			tempInt=addService(addNumberDto.getFirstnumber(), addNumberDto.getSecondnumber());
		}
		return tempInt;
	}
	
	public int addService(int num1, int num2) {
		return num1 + num2;
	}

	public String getChangeDay(Date date, int offset) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.add(Calendar.DAY_OF_YEAR, offset);
		Date newDate = c.getTime();
		return newDate.toString();
	}

	public String uploadFile(byte[] fileBytes, String fileName) {
		FileOutputStream out = null;
		String uploadResult;
		try {
			// 上传文件存放路径
			String newFile = uploadFile + fileName;
			out = new FileOutputStream(newFile);
			try {
				out.write(fileBytes);
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			uploadResult = "FileNotFound";
			return uploadResult;
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		uploadResult = "upLoadSuccess";
		return uploadResult;
	}

	public String checkFileExist(String fileName) {
		File file = new File(fileName);
		if (file.exists()) {
			return "FileExist";
		} else {
			return "FileNotExist";
		}
	}
}
